﻿#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initTreeWidget();
}

MainWindow::~MainWindow()
{
    delete ui;
}

//初始化树控件
void MainWindow::initTreeWidget()
{
    m_CurrentDate = QDate::currentDate(); //获取系统日期

    licenseModule = new QTreeWidget(this);
    ui->verticalLayout->addWidget(licenseModule);
    licenseModule->setHeaderHidden(true);
    licenseModule->setAlternatingRowColors(true);

    QTreeWidgetItem* item1 = new QTreeWidgetItem(licenseModule);
    item1->setText(0,"XX单座");
    item1->setCheckState(0,Qt::Unchecked); //添加复选框，起始为未勾选
    //Qt::ItemIsSelectable表示可选的
    //Qt::ItemIsUserCheckable项目上是否有复选框
    //Qt::ItemIsEnabled 项目上是否没有被禁用（Enabled可用/Disabled禁用）
    item1->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item1,1001);

    QTreeWidgetItem* item2 = new QTreeWidgetItem(licenseModule);
    item2->setText(0,"XX双座");
    item2->setCheckState(0,Qt::Unchecked); //添加复选框，起始为未勾选
    item2->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item2,1002);

    QTreeWidgetItem* item3 = new QTreeWidgetItem(licenseModule);
    item3->setText(0,"XXA");
    item3->setCheckState(0,Qt::Unchecked); //添加复选框，起始为未勾选
    item3->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item3,1003);

    QTreeWidgetItem *item3_1 = new QTreeWidgetItem(item3);        //添加子节点
    item3_1->setText(0,"FC");
    item3_1->setCheckState(0,Qt::Unchecked);
    item3_1->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item3_1,10030001);

    QTreeWidgetItem* item4 = new QTreeWidgetItem(licenseModule);
    item4->setText(0,"XXB");
    item4->setCheckState(0,Qt::Unchecked); //添加复选框，起始为未勾选
    item4->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item4,1004);

    QTreeWidgetItem *item4_1 = new QTreeWidgetItem(item4);        //添加子节点
    item4_1->setText(0,"FC");
    item4_1->setCheckState(0,Qt::Unchecked);
    item4_1->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item4_1,10040001);

    QTreeWidgetItem* item5 = new QTreeWidgetItem(licenseModule);
    item5->setText(0,"XXC");
    item5->setCheckState(0,Qt::Unchecked); //添加复选框，起始为未勾选
    item5->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item5,1005);

    QTreeWidgetItem *item5_1 = new QTreeWidgetItem(item5);        //添加子节点
    item5_1->setText(0,"FC");
    item5_1->setCheckState(0,Qt::Unchecked);
    item5_1->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item5_1,10050001);

    QTreeWidgetItem *item5_2 = new QTreeWidgetItem(item5);        //添加子节点
    item5_2->setText(0,"1553B");
    item5_2->setCheckState(0,Qt::Unchecked);
    item5_2->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    m_PlaneTypeIDItemMap.insert(item5_2,10050002);

    //注意：信号一定只声明变量类型，不要加变量名，是否会报错，找不到该信号
    connect(licenseModule,SIGNAL(itemClicked(QTreeWidgetItem *, int)),this,SLOT(treeCheck(QTreeWidgetItem *, int)));
}

//处理一级节点的复选框状态
void MainWindow::treeCheck(QTreeWidgetItem* item, int column)
{
    if(Qt::Checked == item->checkState(0)) //若被选中
    {
        int count = item->childCount(); //得到选中的子节点个数
        if(count>0){ //若大于0，说明选中的是父节点，则将全部的子节点选中
            for (int i=0;i<count;i++) {
                item->child(i)->setCheckState(0,Qt::Checked);
                //将当前选中的item对应的机型id存起来
                if(m_PlaneTypeIDItemMap.contains(item->child(i))){
                    if(!judgeRepeat(item->child(i))){  //如果没有保存机型id信息，则保存该机型id
                        m_LicensePlaneTypeVec.append(m_PlaneTypeIDItemMap[item->child(i)]);
                    }
                }
            }
        }
        else{  //否则选中的节点没有子节点
            partiallyCheck(item,1);  //将节点传到函数中进行继续操作
        }
    }
    else if(Qt::Unchecked == item->checkState(0)){  //没有被选中
        int count = item->childCount();  //获得子节点个数
        if(count>0){
            for (int i=0;i<count;i++) {
                item->child(i)->setCheckState(0,Qt::Unchecked);
                //判断该item对应的机型id是否被保存，如果被保存则移除
                if(judgeRepeat(item->child(i))){  //判断是否保存有机型id信息，进行移除操作
                    m_LicensePlaneTypeVec.remove(m_PlaneTypeIDItemMap[item->child(i)]);
                }
            }
        }
        else{
            partiallyCheck(item,0);
        }
    }
}

//如果选择的为二级节点，则继续操作
void MainWindow::partiallyCheck(QTreeWidgetItem *item, int checkState)
{
    //得到节点的父节点，首先判断是否为空，为空说明是一级节点，将机型id保存后直接退出
    QTreeWidgetItem* parent = item->parent();
    if(parent==nullptr){
        if(checkState) //如果是选中状态，则将item对应的机型id存起来
        {
            if(m_PlaneTypeIDItemMap.contains(item)){
                if(!judgeRepeat(item)){  //如果没有保存机型id信息，则保存该机型id
                    m_LicensePlaneTypeVec.append(m_PlaneTypeIDItemMap[item]);
                }
            }
        }
        else{ //如果是未选中状态，判断该item对应的机型id是否被保存，如果被保存则移除
            if(judgeRepeat(item)){  //判断是否保存有机型id信息，进行移除操作
                m_LicensePlaneTypeVec.remove(m_PlaneTypeIDItemMap[item]);
            }
        }
        return;
    }

    int selectedCount = 0; //记录被选中的子节点个数
    int count = parent->childCount(); //记录子节点个数
    for (int i=0; i<count;i++) { //父节点下的所有子节点，记录选中的子节点个数
        if(parent->child(i)->checkState(0) == Qt::Checked){
            //将当前选中的item对应的机型id存起来
            if(m_PlaneTypeIDItemMap.contains(parent->child(i))){
                if(!judgeRepeat(parent->child(i))){  //如果没有保存机型id信息，则保存该机型id
                    m_LicensePlaneTypeVec.append(m_PlaneTypeIDItemMap[parent->child(i)]);
                }
            }
            selectedCount++;
        }
        else{ //如果是没选中的，则对比保存的机型id信息，进行移除操作
            if(judgeRepeat(parent->child(i))){  //判断是否保存有机型id信息，进行移除操作
                m_LicensePlaneTypeVec.remove(m_PlaneTypeIDItemMap[parent->child(i)]);
            }
        }
        if(selectedCount<=0){  //等于0说明没有子节点
            parent->setCheckState(0,Qt::Unchecked);
        }
        else if(selectedCount>0&&selectedCount<count){ //若大于0且小于总的子节点数，说明选中了一部分，则将父节点设置为半选中
            parent->setCheckState(0,Qt::PartiallyChecked);
        }
        else{  //否则，全部选中
            parent->setCheckState(0,Qt::Checked);
        }
    }
}

//机型id容器去重判断
int MainWindow::judgeRepeat(QTreeWidgetItem* item)
{
    QVector<int>::iterator iter;
    if(m_LicensePlaneTypeVec.count()>1){
        for(iter=m_LicensePlaneTypeVec.begin();iter!=m_LicensePlaneTypeVec.end();iter++){
            if(m_PlaneTypeIDItemMap[item] == *iter){
                return 1;
            }
        }
    }
    return 0;
}

//重置控件内容
void MainWindow::on_push_clear_clicked()
{
    //清空机器码和授权码
    ui->leMachineCode->setText("");
    ui->leLicenseCode->setText("");

    //清空授权机型模块
    int count = licenseModule->topLevelItemCount();
    if(count>0){  //有一级节点才处理清空复选框操作
        for(int i =0 ; i <count; i++){
            licenseModule->topLevelItem(i)->setCheckState(0,Qt::Unchecked);
        }
    }

    //重置开始和结束日期
    ui->deStart->setDate(QDate::currentDate());
    ui->deEnd->setDate(QDate::currentDate());
}

//复制授权码到剪切板
void MainWindow::on_push_copy_clicked()
{
    QClipboard *clipboard=QApplication::clipboard();
    clipboard->setText(ui->leLicenseCode->text());
}

//生成授权码
void MainWindow::on_push_Authorization_clicked()
{
    //获取机器码
    m_MachineCodeStr = ui->leMachineCode->text();
    if(m_MachineCodeStr.isEmpty()){
        QMessageBox::critical(this,tr("错误提示"),tr("请填写机器码"));
        return;
    }

    //获取授权机型模块 TODO逻辑还需要修改
    QStringList tempList;
    for(int i =0; i<m_LicensePlaneTypeVec.count();i++){
        tempList.append(QString::number(m_LicensePlaneTypeVec[i]));
    }
    m_LicensePlaneTypeStr = tempList.join("-"); //添加分隔符
    qDebug()<<"str is:"<< m_LicensePlaneTypeStr;

    //获取授权时间
    m_StartDate = ui->deStart->date();
    m_EndDate = ui->deEnd->date();
    if(m_StartDate>=m_EndDate){
        QMessageBox::critical(this,tr("错误提示"),tr("请选择正确的日期"));
        return;
    }
    else{
        m_LicenseDateRangeStr = m_StartDate.toString()+"-"+m_EndDate.toString();
    }

    //将三个串码组成字符串，分隔符为“-”
    m_BeforeEncryption = m_MachineCodeStr+"-"+m_LicensePlaneTypeStr+"-"+m_LicenseDateRangeStr;

    //AES加密
    ui->leLicenseCode->setText(AES_encryption(m_BeforeEncryption,AES_KEY));
}

QString MainWindow::AES_encryption(const QString  data, const QString key)
{
    QAESEncryption encryption(QAESEncryption::AES_128, QAESEncryption::ECB, QAESEncryption::ZERO);
    QByteArray hashKey = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5);
    QByteArray encodedText = encryption.encode(data.toUtf8(), hashKey);
    QString encodeTextStr = QString::fromLatin1(encodedText.toBase64());

    return encodeTextStr;
}
